# -*- coding: utf-8 -*-

import webapp2

from models.usuario import Usuario
from models.persona import Persona as PersonaModel
from models.mecanica import Mecanica as MecanicaModel

from pages.basePage import BaseHandler
import pages.home as home

from pages.signup import Signup
from pages.cenario import Cenario
from pages.escolherPersona import EscolherPersona
from pages.criarMecanica import CriarMecanica
from pages.escolherMecanica import EscolherMecanica
from pages.criarPersona import CriarPersona
from pages.criarPersona import CriarPersona2
from pages.infoPersona import InfoPersona
from pages.similares import Similares
from pages.persona import Persona

import jinja2
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainPage(BaseHandler):
    def get(self):
        userId = self.session.get('userid')
        user = None
        if userId is not None:
            user = Usuario.get_by_id(userId)
        if user is not None:
            self.redirect('/home')
            return
        else:
            template = jinja_environment.get_template('pages/html/index.htm')
            self.response.out.write(template.render())
            
class Login(BaseHandler):
    def post(self):
        
        email = self.request.get('username')
        password = self.request.get('password')
        Usuario.gql('WHERE email = :1 and senha = :2', email, password)
        
        user = Usuario.gql('WHERE email = :1', email)
        if user.count() == 1:
            user = user[0]
            if user.senha == password:
                self.session['userid'] = user.key().id()
                self.redirect('/home')
                return
        self.redirect('/?erro=UsuarioInexistenteOuSenhaInvalida')        

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'chavesecretarockandroll',
}

class Login2(BaseHandler):
    def get(self):
        template = jinja_environment.get_template('pages/html/login.html')
        self.response.out.write(template.render())
        
class Logout(BaseHandler):
    def post(self):
        Logout.get(self)
    def get(self):      
        self.session['userid'] = None
        self.redirect('/')
        
class Image(BaseHandler):
    def get(self):
        userId = self.session.get('userid')
        user = Usuario.get_by_id(userId)
        if user is None:
            self.redirect('/')
            return
        
        iid = int(self.request.get("id"))
        tipo = self.request.get('tipo')
        if tipo == 'p':
            persona = PersonaModel.get_by_id(iid)        
            if persona is None:
                self.error(404)
                return        
            if persona.imagem:
                self.response.headers['Content-Type'] = "image/png"
                self.response.out.write(persona.imagem)
            else:
                self.error(404)
                return
        elif tipo == 'm':
            mecanica = MecanicaModel.get_by_id(iid)        
            if mecanica is None:
                self.error(404)
                return        
            if mecanica.imagem:
                self.response.headers['Content-Type'] = "image/png"
                self.response.out.write(mecanica.imagem)
            else:
                self.error(404)
                return
        else:
            self.error(404)
            return
                
                

app = webapp2.WSGIApplication([('/', MainPage),
                               ('/home', home.Home),
                               ('/login', Login),
                               ('/login2', Login2),
                               ('/logout', Logout),
                               ('/signup', Signup),
                               ('/img', Image),
                               ('/redu', home.Redu),
                               ('/escolherPersona', EscolherPersona),
                               ('/cenario', Cenario),
                               ('/criarMecanica', CriarMecanica),
                               ('/escolherMecanica', EscolherMecanica),
                               ('/criarPersona', CriarPersona),
                               ('/infoPersona', InfoPersona),
                               ('/similares', Similares),
                               ('/concluiCriarPersona', CriarPersona2),
                               ('/teste', Persona)],
                              config=config,
                              debug=True)